package feedback

import (
	"strings"

	"github.com/gin-gonic/gin"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/response"
	"gpt-api/pkg/service"
	"gpt-api/pkg/util"
)

type Handler struct {
	feedbackImpl *service.FeedbackImpl
}

func New() *Handler {
	return &Handler{
		feedbackImpl: service.NewFeedbackImpl(),
	}
}

func (h *Handler) GetCategory(c *gin.Context) (err error) {
	var req struct {
		Project string `form:"project" binding:"required"`
	}
	if err = c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}
	lang := ginplus.Language(c)
	resp, err := h.feedbackImpl.ListCategory(lang, req.Project)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, resp)

}

func (h *Handler) Submit(c *gin.Context) (err error) {
	var req response.SubmitReq
	platform := ginplus.GetPlatform(c)
	version := ginplus.GetVersion(c)
	model := ginplus.GetDeviceModel(c)
	if err = c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}
	// PC and H5 model set user-agent
	p := strings.ToLower(strings.TrimSpace(platform))
	if p == "h5" || p == "pc" {
		model = ginplus.UserAgent(c)
	}
	if len(model) > 500 {
		model = model[:500]
	}
	if err = h.feedbackImpl.Submit(req, platform, version, model); err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	return ginplus.ReplyJSON(c, nil)
}

func (h *Handler) ListQues(c *gin.Context) (err error) {
	var req struct {
		util.PageFooter
		Project    *string `form:"project" binding:"required"`
		CategoryId *int    `form:"category_id"`
		Status     *int    `form:"status"`
	}
	if err = c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}
	lang := ginplus.Language(c)
	resp, err := h.feedbackImpl.ListQues(req.Project, req.CategoryId, req.Status, req.Page, req.Size, lang)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	return ginplus.ReplyJSON(c, resp)

}

func (h *Handler) QuestionManage(c *gin.Context) (err error) {
	var req struct {
		Id     int `json:"id"`
		Status int `json:"status"`
	}
	if err = c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}
	if err = h.feedbackImpl.QuesManage(req.Id, req.Status); err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	return ginplus.ReplyJSON(c, nil)
}
